<template>
  <div class="sign-container" v-if="show">
    <!-- 第一部分：发起签到 -->
    <div class="sign-section" v-if="!isSignStarted">
      <input type="number" v-model="selectedTime" class="sign-input" placeholder="选择时间(单位:分钟)" />
      <button class="sign-button" @click="startSigning">开始签到</button>
    </div>

    <!-- 第二部分：响应签到 -->
    <div class="sign-section" v-if="isSignStarted && !isSignEnded">
      <p class="countdown">距离签到结束还有：{{ countdown }}</p>
      <button class="sign-button" @click="confirmSign">确认签到</button>
    </div>

    <!-- 第三部分：签到结束 -->
    <div class="sign-section" v-if="isSignEnded">
      <p class="sign-result">签到人数：{{ signCount }}</p>
      <ul class="sign-list">
        <li>签到名单：</li>
        <li v-for="signer in signers" :key="signer.id">
          {{ signer.name }}&nbsp;
        </li>
      </ul>
      <button class="sign-button" @click="showSignUp()">签到结束</button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from "vue";
import { useWebsocket } from "../../hooks";
import store from "@/store";

const selectedTime = ref("");
const isSignStarted = ref(false);
const isSignEnded = ref(false);
const countdown = ref(0);
const signCount = ref(0);
const signers = reactive([]);
const socket = useWebsocket(handelMessage); //连接socket
const userData = store.state.userData;
const roomData = store.state.roomData;
const show = ref(false);

//显示和隐藏签到页面
function showSignUp() {
  show.value = !show.value;
  //还原签到开始页面
  isSignStarted.value = false;
  isSignEnded.value = false;
}

//开始签到
function startSigning() {
  if (selectedTime.value) {
    //发送开始签到的消息
    socket.send(
      JSON.stringify({
        userId: userData.userId,
        roomId: roomData.roomId,
        selectedTime: selectedTime.value,
        type: "startSignUp",
      })
    );
  }
}

//开始倒计时
var cutTime;
function startCountdown(minutes) {
  let lastTime = minutes * 60;
  let lastMinutes = Math.floor(lastTime / 60);
  let lastSeconds = lastTime - lastMinutes * 60;
  //每秒变换一次数值
  cutTime = setInterval(() => {
    lastTime--;
    lastMinutes = Math.floor(lastTime / 60);
    lastSeconds = lastTime - lastMinutes * 60;
    countdown.value = lastMinutes
      ? lastMinutes + "分" + lastSeconds + "秒"
      : lastSeconds + "秒";
    if (lastTime == 0) {
      //定时结束
      endSigning(true);
    }
  }, 1000);
}

function confirmSign() {
  show.value = !show.value
  //发送确认信息
  socket.send(
    JSON.stringify({
      userId: userData.userId,
      userName: userData.username,
      roomId: roomData.roomId,
      type: "confirmSign",
    })
  );
}

function endSigning(flag) {
  isSignEnded.value = true;
  clearInterval(cutTime);
  if (flag) {
    show.value = !show.value
    //发送结束信息
    socket.send(
      JSON.stringify({
        userId: userData.userId,
        roomId: roomData.roomId,
        type: "endSignUp",
      })
    );
  }
}

function handelMessage(event) {
  const data = JSON.parse(event.data);
  //防止用户重复收到消息
  //   if (userData.userId == data.userId) {
  //     return;
  //   }
  // console.log("socket发送的" + data.type, data);
  switch (data.type) {
    case "startSignUp":
      //展示签到页面
      show.value = true;
      //关掉开始签到页面
      isSignStarted.value = true;
      //打开响应签到页面
      isSignEnded.value = false;
      //设置签到时间初值并开始倒计时
      startCountdown(data.selectedTime);
      break;
    case "endSignUp":
      endSigning(false);
      break;
    case "confirmSign":
      let flag = true
      signers.forEach(function (item) {
        if (item.id == data.userId) {
          flag = false
        }
      })
      if (flag) {
        signers.push({ id: data.userId, name: data.userName });
        signCount.value++;
      }
      break;
  }
}

onUnmounted(() => {
  clearInterval(cutTime);
});

defineExpose({
  showSignUp,
});
</script>

<style scoped>
.sign-container {
  height: 11.25rem;
  width: 25rem;
  border-radius: 20px;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 1rem;
  box-sizing: border-box;
  z-index: 100000000;
  position: fixed;
  bottom: 8rem;
  left: 2rem;
  box-shadow: 0px 4px 6px gray;
}

.sign-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1rem;
}

.sign-input {
  width: 100%;
  padding: 0.5rem;
  border-radius: 10px;
  border: 1px solid #ccc;
}

.sign-button {
  padding: 0.5rem 1rem;
  border-radius: 10px;
  background-color: #007bff;
  color: #fff;
  border: none;
  cursor: pointer;
}

.countdown,
.sign-result {
  font-size: 1rem;
  margin-bottom: 0.5rem;
}

.sign-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.sign-list li {
  margin-bottom: 0.5rem;
  display: inline;
}
</style>